package sample.xml;

import java.io.File;
import java.io.FileWriter;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class XMLDocumentBuilder {
	private Document d;

	/* use DocumentHelper to create a document */
	public String createDocument() throws Exception{
		d = DocumentHelper.createDocument();
		return d.asXML();
	}

	/* add a root element for the document */
	public Element addRootElement(String elementName) throws Exception {
		Element root = d.addElement("table");
		root.addAttribute("name",elementName);
		return root;
	}

	/* add new element to the document with a given name and its parent Element */
	public Element addSubElement(Element parent, String name)throws Exception {
		Element root = parent.addElement(name);
		return root;
	}

	/* add attribute for an element with given attribute name and attribute value */
	public void addAttribute(Element element, String attribute,String value) throws Exception {
		element.addAttribute(attribute, value);
	}

	/* set text value to an element */
	public void addText(Element element, String value) throws Exception {
		if (value.isEmpty()) {
			value = "null";
		}
		element.addText(value);
	}

	/* get document content */
	public String getXMLStr() throws Exception{
		return suitUp(d.asXML());
	}

	/* save the document to a given place */
	public void writeXML(String filepath) throws Exception{
		FileWriter out = new FileWriter(filepath);
		d.write(out);
		out.close();
	}

	/* give the output xml file a decent look */
	private String suitUp(String xml) throws Exception{
		xml = xml.replaceAll("<", "\n<");
		xml = xml.replaceAll("\n</", "</");
		xml = xml.replaceAll("</table", "\n</table");
		xml = xml.replaceAll("</row", "\n</row");
		xml = xml.replaceAll("<","\t<");
		xml = xml.replaceAll("\t</", "</");
		xml = xml.replaceAll("\t<row>", "<row>");
		xml = xml.replaceAll("\t</row>", "</row>");
		xml = xml.replaceAll("\t<\\?xml", "<\\?xml");
		xml = xml.replaceAll("\t<table", "<table");
		xml = xml.replaceAll("\t</table", "</table");
		return xml;
	}

	/* create a document using a given xml file */
	public XMLDocumentBuilder(File xmlFile) throws Exception {
		SAXReader reader = new SAXReader();
		d = reader.read(xmlFile);
	}
	
	public XMLDocumentBuilder(){

	}
}
